import { ExecutionContext, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { AuthGuard } from "@nestjs/passport";

import { SKIP_LOCAL_AUTH_KEY } from "../decorator/skip-auth.decorator";

/**
 * 本地认证守卫
 */
@Injectable()
export class LocalAuthGuard extends AuthGuard("local") {
    constructor(private reflector: Reflector) {
        super();
    }

    // 判断是否有跳过认证的装饰器
    canActivate(context: ExecutionContext) {
        const isPublic = this.reflector.getAllAndOverride<boolean>(SKIP_LOCAL_AUTH_KEY, [
            context.getHandler(),
            context.getClass()
        ]);
        if (isPublic) {
            return true;
        }
        return super.canActivate(context);
    }
}
